package edu.lfsfxy.myschool.controller;

import edu.lfsfxy.myschool.dao.StudentDao;
import edu.lfsfxy.myschool.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    StudentDao studentDao;
    @RequestMapping("/findAll")
    public String findAll(Model model){
        List<Student> students = studentDao.findAll();
        model.addAttribute("students",students);
        return "stuList";
    }
    @RequestMapping("/delete")
    public String delete(int sno,Model model){
        int i = studentDao.delete(sno);
        model.addAttribute("i",i);
        return "forward:/student/findAll";
    }
    @RequestMapping("/add")
    public String add(Student stu){
        int i = studentDao.add(stu);
        return "forward:/student/findAll";
    }
    @RequestMapping("/findBySno")
    public String update(int sno,Model model){
        Student student = studentDao.findBySno(sno);
        model.addAttribute("stu",student);
        return "stuUpdate";
    }
    @RequestMapping("/update")
    public String update1(Student stu,Model model){
        try {
            int i = studentDao.update(stu);
            if (i>0){
                return "forward:/student/findAll";
            }
            else{
                model.addAttribute("err","修改未成功");
                model.addAttribute("stu",stu);
                return "stuUpdate";
            }
        } catch (Exception e) {
            model.addAttribute("err","修改未成功"+e.getMessage());
            model.addAttribute("stu",stu);
            return "stuUpdate";
        }
    }
}
